home *** CD-ROM | disk | FTP | other *** search
/ MacAddict 117 / MacAddict 117.dmg / Software / Utilities / Tidy Up 1.0.9 (shareware).dmg / Tidy Up! / Tidy Up!.app / Contents / Resources / MP3 / Info.pm < prev    next >
Encoding:
Perl POD Document  |  2006-02-09  |  38.6 KB  |  1,689 lines

  1. package MP3::Info;
  2. require 5.006;
  3. use overload;
  4. use strict;
  5. use Carp;
  6.  
  7. use vars qw(
  8.     @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION $REVISION
  9.     @mp3_genres %mp3_genres @winamp_genres %winamp_genres $try_harder
  10.     @t_bitrate @t_sampling_freq @frequency_tbl %v1_tag_fields
  11.     @v1_tag_names %v2_tag_names %v2_to_v1_names $AUTOLOAD
  12.     @mp3_info_fields
  13. );
  14.  
  15. @ISA = 'Exporter';
  16. @EXPORT = qw(
  17.     set_mp3tag get_mp3tag get_mp3info remove_mp3tag
  18.     use_winamp_genres
  19. );
  20. @EXPORT_OK = qw(@mp3_genres %mp3_genres use_mp3_utf8);
  21. %EXPORT_TAGS = (
  22.     genres    => [qw(@mp3_genres %mp3_genres)],
  23.     utf8    => [qw(use_mp3_utf8)],
  24.     all    => [@EXPORT, @EXPORT_OK]
  25. );
  26.  
  27. # $Id: Info.pm,v 1.16 2004/12/31 07:31:27 pudge Exp $
  28. ($REVISION) = ' $Revision: 1.16 $ ' =~ /\$Revision:\s+([^\s]+)/;
  29. $VERSION = '1.10';
  30.  
  31. =pod
  32.  
  33. =head1 NAME
  34.  
  35. MP3::Info - Manipulate / fetch info from MP3 audio files
  36.  
  37. =head1 SYNOPSIS
  38.  
  39.     #!perl -w
  40.     use MP3::Info;
  41.     my $file = 'Pearls_Before_Swine.mp3';
  42.     set_mp3tag($file, 'Pearls Before Swine', q"77's",
  43.         'Sticks and Stones', '1990',
  44.         q"(c) 1990 77's LTD.", 'rock & roll');
  45.  
  46.     my $tag = get_mp3tag($file) or die "No TAG info";
  47.     $tag->{GENRE} = 'rock';
  48.     set_mp3tag($file, $tag);
  49.  
  50.     my $info = get_mp3info($file);
  51.     printf "$file length is %d:%d\n", $info->{MM}, $info->{SS};
  52.  
  53. =cut
  54.  
  55. {
  56.     my $c = -1;
  57.     # set all lower-case and regular-cased versions of genres as keys
  58.     # with index as value of each key
  59.     %mp3_genres = map {($_, ++$c, lc, $c)} @mp3_genres;
  60.  
  61.     # do it again for winamp genres
  62.     $c = -1;
  63.     %winamp_genres = map {($_, ++$c, lc, $c)} @winamp_genres;
  64. }
  65.  
  66. =pod
  67.  
  68.     my $mp3 = new MP3::Info $file;
  69.     $mp3->title('Perls Before Swine');
  70.     printf "$file length is %s, title is %s\n",
  71.         $mp3->time, $mp3->title;
  72.  
  73.  
  74. =head1 DESCRIPTION
  75.  
  76. =over 4
  77.  
  78. =item $mp3 = MP3::Info-E<gt>new(FILE)
  79.  
  80. OOP interface to the rest of the module.  The same keys
  81. available via get_mp3info and get_mp3tag are available
  82. via the returned object (using upper case or lower case;
  83. but note that all-caps "VERSION" will return the module
  84. version, not the MP3 version).
  85.  
  86. Passing a value to one of the methods will set the value
  87. for that tag in the MP3 file, if applicable.
  88.  
  89. =cut
  90.  
  91. sub new {
  92.     my($pack, $file) = @_;
  93.  
  94.     my $info = get_mp3info($file) or return undef;
  95.     my $tags = get_mp3tag($file) || { map { ($_ => undef) } @v1_tag_names };
  96.     my %self = (
  97.         FILE        => $file,
  98.         TRY_HARDER    => 0
  99.     );
  100.  
  101.     @self{@mp3_info_fields, @v1_tag_names, 'file'} = (
  102.         @{$info}{@mp3_info_fields},
  103.         @{$tags}{@v1_tag_names},
  104.         $file
  105.     );
  106.  
  107.     return bless \%self, $pack;
  108. }
  109.  
  110. sub can {
  111.     my $self = shift;
  112.     return $self->SUPER::can(@_) unless ref $self;
  113.     my $name = uc shift;
  114.     return sub { $self->$name(@_) } if exists $self->{$name};
  115.     return undef;
  116. }
  117.  
  118. sub AUTOLOAD {
  119.     my($self) = @_;
  120.     (my $name = uc $AUTOLOAD) =~ s/^.*://;
  121.  
  122.     if (exists $self->{$name}) {
  123.         my $sub = exists $v1_tag_fields{$name}
  124.             ? sub {
  125.                 if (defined $_[1]) {
  126.                     $_[0]->{$name} = $_[1];
  127.                     set_mp3tag($_[0]->{FILE}, $_[0]);
  128.                 }
  129.                 return $_[0]->{$name};
  130.             }
  131.             : sub {
  132.                 return $_[0]->{$name}
  133.             };
  134.  
  135.         no strict 'refs';
  136.         *{$AUTOLOAD} = $sub;
  137.         goto &$AUTOLOAD;
  138.  
  139.     } else {
  140.         carp(sprintf "No method '$name' available in package %s.",
  141.             __PACKAGE__);
  142.     }
  143. }
  144.  
  145. sub DESTROY {
  146.  
  147. }
  148.  
  149.  
  150. =item use_mp3_utf8([STATUS])
  151.  
  152. Tells MP3::Info to (or not) return TAG info in UTF-8.
  153. TRUE is 1, FALSE is 0.  Default is TRUE, if available.
  154.  
  155. Will only be able to turn it on if Encode is available.  ID3v2
  156. tags will be converted to UTF-8 according to the encoding specified
  157. in each tag; ID3v1 tags will be assumed Latin-1 and converted
  158. to UTF-8.
  159.  
  160. Function returns status (TRUE/FALSE).  If no argument is supplied,
  161. or an unaccepted argument is supplied, function merely returns status.
  162.  
  163. This function is not exported by default, but may be exported
  164. with the C<:utf8> or C<:all> export tag.
  165.  
  166. =cut
  167.  
  168. my $unicode_module = eval { require Encode; require Encode::Guess };
  169. my $UNICODE = use_mp3_utf8($unicode_module ? 1 : 0);
  170.  
  171. sub use_mp3_utf8 {
  172.     my($val) = @_;
  173.     if ($val == 1) {
  174.         if ($unicode_module) {
  175.             $UNICODE = 1;
  176.             $Encode::Guess::NoUTFAutoGuess = 1;
  177.         }
  178.     } elsif ($val == 0) {
  179.         $UNICODE = 0;
  180.     }
  181.     return $UNICODE;
  182. }
  183.  
  184. =pod
  185.  
  186. =item use_winamp_genres()
  187.  
  188. Puts WinAmp genres into C<@mp3_genres> and C<%mp3_genres>
  189. (adds 68 additional genres to the default list of 80).
  190. This is a separate function because these are non-standard
  191. genres, but they are included because they are widely used.
  192.  
  193. You can import the data structures with one of:
  194.  
  195.     use MP3::Info qw(:genres);
  196.     use MP3::Info qw(:DEFAULT :genres);
  197.     use MP3::Info qw(:all);
  198.  
  199. =cut
  200.  
  201. sub use_winamp_genres {
  202.     %mp3_genres = %winamp_genres;
  203.     @mp3_genres = @winamp_genres;
  204.     return 1;
  205. }
  206.  
  207. =pod
  208.  
  209. =item remove_mp3tag (FILE [, VERSION, BUFFER])
  210.  
  211. Can remove ID3v1 or ID3v2 tags.  VERSION should be C<1> for ID3v1
  212. (the default), C<2> for ID3v2, and C<ALL> for both.
  213.  
  214. For ID3v1, removes last 128 bytes from file if those last 128 bytes begin
  215. with the text 'TAG'.  File will be 128 bytes shorter.
  216.  
  217. For ID3v2, removes ID3v2 tag.  Because an ID3v2 tag is at the
  218. beginning of the file, we rewrite the file after removing the tag data.
  219. The buffer for rewriting the file is 4MB.  BUFFER (in bytes) ca
  220. change the buffer size.
  221.  
  222. Returns the number of bytes removed, or -1 if no tag removed,
  223. or undef if there is an error.
  224.  
  225. =cut
  226.  
  227. sub remove_mp3tag {
  228.     my($file, $version, $buf) = @_;
  229.     my($fh, $return);
  230.  
  231.     $buf ||= 4096*1024;  # the bigger the faster
  232.     $version ||= 1;
  233.  
  234.     if (not (defined $file && $file ne '')) {
  235.         $@ = "No file specified";
  236.         return undef;
  237.     }
  238.  
  239.     if (not -s $file) {
  240.         $@ = "File is empty";
  241.         return undef;
  242.     }
  243.  
  244.     if (ref $file) { # filehandle passed
  245.         $fh = $file;
  246.     } else {
  247.         if (not open $fh, '+<', $file) {
  248.             $@ = "Can't open $file: $!";
  249.             return undef;
  250.         }
  251.     }
  252.  
  253.     binmode $fh;
  254.  
  255.     if ($version eq 1 || $version eq 'ALL') {
  256.         seek $fh, -128, 2;
  257.         my $tell = tell $fh;
  258.         if (<$fh> =~ /^TAG/) {
  259.             truncate $fh, $tell or carp "Can't truncate '$file': $!";
  260.             $return += 128;
  261.         }
  262.     }
  263.  
  264.     if ($version eq 2 || $version eq 'ALL') {
  265.         my $v2h = _get_v2head($fh);
  266.         if ($v2h) {
  267.             local $\;
  268.             seek $fh, 0, 2;
  269.             my $eof = tell $fh;
  270.             my $off = $v2h->{tag_size};
  271.  
  272.             while ($off < $eof) {
  273.                 seek $fh, $off, 0;
  274.                 read $fh, my($bytes), $buf;
  275.                 seek $fh, $off - $v2h->{tag_size}, 0;
  276.                 print $fh $bytes;
  277.                 $off += $buf;
  278.             }
  279.  
  280.             truncate $fh, $eof - $v2h->{tag_size}
  281.                 or carp "Can't truncate '$file': $!";
  282.             $return += $v2h->{tag_size};
  283.         }
  284.     }
  285.  
  286.     _close($file, $fh);
  287.  
  288.     return $return || -1;
  289. }
  290.  
  291.  
  292. =pod
  293.  
  294. =item set_mp3tag (FILE, TITLE, ARTIST, ALBUM, YEAR, COMMENT, GENRE [, TRACKNUM])
  295.  
  296. =item set_mp3tag (FILE, $HASHREF)
  297.  
  298. Adds/changes tag information in an MP3 audio file.  Will clobber
  299. any existing information in file.
  300.  
  301. Fields are TITLE, ARTIST, ALBUM, YEAR, COMMENT, GENRE.  All fields have
  302. a 30-byte limit, except for YEAR, which has a four-byte limit, and GENRE,
  303. which is one byte in the file.  The GENRE passed in the function is a
  304. case-insensitive text string representing a genre found in C<@mp3_genres>.
  305.  
  306. Will accept either a list of values, or a hashref of the type
  307. returned by C<get_mp3tag>.
  308.  
  309. If TRACKNUM is present (for ID3v1.1), then the COMMENT field can only be
  310. 28 bytes.
  311.  
  312. ID3v2 support may come eventually.  Note that if you set a tag on a file
  313. with ID3v2, the set tag will be for ID3v1[.1] only, and if you call
  314. C<get_mp3tag> on the file, it will show you the (unchanged) ID3v2 tags,
  315. unless you specify ID3v1.
  316.  
  317. =cut
  318.  
  319. sub set_mp3tag {
  320.     my($file, $title, $artist, $album, $year, $comment, $genre, $tracknum) = @_;
  321.     my(%info, $oldfh, $ref, $fh);
  322.     local %v1_tag_fields = %v1_tag_fields;
  323.  
  324.     # set each to '' if undef
  325.     for ($title, $artist, $album, $year, $comment, $tracknum, $genre,
  326.         (@info{@v1_tag_names}))
  327.         {$_ = defined() ? $_ : ''}
  328.  
  329.     ($ref) = (overload::StrVal($title) =~ /^(?:.*\=)?([^=]*)\((?:[^\(]*)\)$/)
  330.         if ref $title;
  331.     # populate data to hashref if hashref is not passed
  332.     if (!$ref) {
  333.         (@info{@v1_tag_names}) =
  334.             ($title, $artist, $album, $year, $comment, $tracknum, $genre);
  335.  
  336.     # put data from hashref into hashref if hashref is passed
  337.     } elsif ($ref eq 'HASH') {
  338.         %info = %$title;
  339.  
  340.     # return otherwise
  341.     } else {
  342.         carp(<<'EOT');
  343. Usage: set_mp3tag (FILE, TITLE, ARTIST, ALBUM, YEAR, COMMENT, GENRE [, TRACKNUM])
  344.        set_mp3tag (FILE, $HASHREF)
  345. EOT
  346.         return undef;
  347.     }
  348.  
  349.     if (not (defined $file && $file ne '')) {
  350.         $@ = "No file specified";
  351.         return undef;
  352.     }
  353.  
  354.     if (not -s $file) {
  355.         $@ = "File is empty";
  356.         return undef;
  357.     }
  358.  
  359.     # comment field length 28 if ID3v1.1
  360.     $v1_tag_fields{COMMENT} = 28 if $info{TRACKNUM};
  361.  
  362.  
  363.     # only if -w is on
  364.     if ($^W) {
  365.         # warn if fields too long
  366.         foreach my $field (keys %v1_tag_fields) {
  367.             $info{$field} = '' unless defined $info{$field};
  368.             if (length($info{$field}) > $v1_tag_fields{$field}) {
  369.                 carp "Data too long for field $field: truncated to " .
  370.                      "$v1_tag_fields{$field}";
  371.             }
  372.         }
  373.  
  374.         if ($info{GENRE}) {
  375.             carp "Genre `$info{GENRE}' does not exist\n"
  376.                 unless exists $mp3_genres{$info{GENRE}};
  377.         }
  378.     }
  379.  
  380.     if ($info{TRACKNUM}) {
  381.         $info{TRACKNUM} =~ s/^(\d+)\/(\d+)$/$1/;
  382.         unless ($info{TRACKNUM} =~ /^\d+$/ &&
  383.             $info{TRACKNUM} > 0 && $info{TRACKNUM} < 256) {
  384.             carp "Tracknum `$info{TRACKNUM}' must be an integer " .
  385.                 "from 1 and 255\n" if $^W;
  386.             $info{TRACKNUM} = '';
  387.         }
  388.     }
  389.  
  390.     if (ref $file) { # filehandle passed
  391.         $fh = $file;
  392.     } else {
  393.         if (not open $fh, '+<', $file) {
  394.             $@ = "Can't open $file: $!";
  395.             return undef;
  396.         }
  397.     }
  398.  
  399.     binmode $fh;
  400.     $oldfh = select $fh;
  401.     seek $fh, -128, 2;
  402.     # go to end of file if no tag, beginning of file if tag
  403.     seek $fh, (<$fh> =~ /^TAG/ ? -128 : 0), 2;
  404.  
  405.     # get genre value
  406.     $info{GENRE} = $info{GENRE} && exists $mp3_genres{$info{GENRE}} ?
  407.         $mp3_genres{$info{GENRE}} : 255;  # some default genre
  408.  
  409.     local $\;
  410.     # print TAG to file
  411.     if ($info{TRACKNUM}) {
  412.         print pack 'a3a30a30a30a4a28xCC', 'TAG', @info{@v1_tag_names};
  413.     } else {
  414.         print pack 'a3a30a30a30a4a30C', 'TAG', @info{@v1_tag_names[0..4, 6]};
  415.     }
  416.  
  417.     select $oldfh;
  418.  
  419.     _close($file, $fh);
  420.  
  421.     return 1;
  422. }
  423.  
  424. =pod
  425.  
  426. =item get_mp3tag (FILE [, VERSION, RAW_V2])
  427.  
  428. Returns hash reference containing tag information in MP3 file.  The keys
  429. returned are the same as those supplied for C<set_mp3tag>, except in the
  430. case of RAW_V2 being set.
  431.  
  432. If VERSION is C<1>, the information is taken from the ID3v1 tag (if present).
  433. If VERSION is C<2>, the information is taken from the ID3v2 tag (if present).
  434. If VERSION is not supplied, or is false, the ID3v1 tag is read if present, and
  435. then, if present, the ID3v2 tag information will override any existing ID3v1
  436. tag info.
  437.  
  438. If RAW_V2 is C<1>, the raw ID3v2 tag data is returned, without any manipulation
  439. of text encoding.  The key name is the same as the frame ID (ID to name mappings
  440. are in the global %v2_tag_names).
  441.  
  442. If RAW_V2 is C<2>, the ID3v2 tag data is returned, manipulating for Unicode if
  443. necessary, etc.  It also takes multiple values for a given key (such as comments)
  444. and puts them in an arrayref.
  445.  
  446. If the ID3v2 version is older than ID3v2.2.0 or newer than ID3v2.4.0, it will
  447. not be read.
  448.  
  449. Strings returned will be in Latin-1, unless UTF-8 is specified (L<use_mp3_utf8>),
  450. (unless RAW_V2 is C<1>).
  451.  
  452. Also returns a TAGVERSION key, containing the ID3 version used for the returned
  453. data (if TAGVERSION argument is C<0>, may contain two versions).
  454.  
  455. =cut
  456.  
  457. sub get_mp3tag {
  458.     my($file, $ver, $raw_v2) = @_;
  459.     my($tag, $v1, $v2, $v2h, %info, @array, $fh);
  460.     $raw_v2 ||= 0;
  461.     $ver = !$ver ? 0 : ($ver == 2 || $ver == 1) ? $ver : 0;
  462.  
  463.     if (not (defined $file && $file ne '')) {
  464.         $@ = "No file specified";
  465.         return undef;
  466.     }
  467.  
  468.     if (not -s $file) {
  469.         $@ = "File is empty";
  470.         return undef;
  471.     }
  472.  
  473.     if (ref $file) { # filehandle passed
  474.         $fh = $file;
  475.     } else {
  476.         if (not open $fh, '<', $file) {
  477.             $@ = "Can't open $file: $!";
  478.             return undef;
  479.         }
  480.     }
  481.  
  482.     binmode $fh;
  483.  
  484.     if ($ver < 2) {
  485.         seek $fh, -128, 2;
  486.         while(defined(my $line = <$fh>)) { $tag .= $line }
  487.  
  488.         if ($tag && $tag =~ /^TAG/) {
  489.             $v1 = 1;
  490.             if (substr($tag, -3, 2) =~ /\000[^\000]/) {
  491.                 (undef, @info{@v1_tag_names}) =
  492.                     (unpack('a3a30a30a30a4a28', $tag),
  493.                     ord(substr($tag, -2, 1)),
  494.                     $mp3_genres[ord(substr $tag, -1)]);
  495.                 $info{TAGVERSION} = 'ID3v1.1';
  496.             } else {
  497.                 (undef, @info{@v1_tag_names[0..4, 6]}) =
  498.                     (unpack('a3a30a30a30a4a30', $tag),
  499.                     $mp3_genres[ord(substr $tag, -1)]);
  500.                 $info{TAGVERSION} = 'ID3v1';
  501.             }
  502.             if ($UNICODE) {
  503.                 for my $key (keys %info) {
  504.                     next unless $info{$key};
  505.                     $info{$key} = Encode::encode_utf8($info{$key});
  506.                 }
  507.             }
  508.         } elsif ($ver == 1) {
  509.             _close($file, $fh);
  510.             $@ = "No ID3v1 tag found";
  511.             return undef;
  512.         }
  513.     }
  514.  
  515.     ($v2, $v2h) = _get_v2tag($fh);
  516.  
  517.     unless ($v1 || $v2) {
  518.         _close($file, $fh);
  519.         $@ = "No ID3 tag found";
  520.         return undef;
  521.     }
  522.  
  523.     if (($ver == 0 || $ver == 2) && $v2) {
  524.         if ($raw_v2 == 1 && $ver == 2) {
  525.             %info = %$v2;
  526.             $info{TAGVERSION} = $v2h->{version};
  527.         } else {
  528.             my $hash = $raw_v2 == 2 ? { map { ($_, $_) } keys %v2_tag_names } : \%v2_to_v1_names;
  529.             for my $id (keys %$hash) {
  530.                 if (exists $v2->{$id}) {
  531.                     my $data1 = $v2->{$id};
  532.  
  533.                     # this is tricky ... if this is an arrayref,
  534.                     # we want to only return one, so we pick the
  535.                     # first one.  but if it is a comment, we pick
  536.                     # the first one where the first charcter after
  537.                     # the language is NULL and not an additional
  538.                     # sub-comment, because that is most likely to be
  539.                     # the user-supplied comment
  540.                     if (ref $data1 && !$raw_v2) {
  541.                         if ($id =~ /^COMM?$/) {
  542.                             my($newdata) = grep /^(....\000)/, @{$data1};
  543.                             $data1 = $newdata || $data1->[0];
  544.                         } else {
  545.                             $data1 = $data1->[0];
  546.                         }
  547.                     }
  548.  
  549.                     $data1 = [ $data1 ] if ! ref $data1;
  550.  
  551.                     for my $data (@$data1) {
  552.                         # TODO : this should only be done for certain frames;
  553.                         # using RAW still gives you access, but we should be smarter
  554.                         # about how individual frame types are handled.  it's not
  555.                         # like the list is infinitely long.
  556.                         $data =~ s/^(.)//; # strip first char (text encoding)
  557.                         my $encoding = $1;
  558.                         my $desc;
  559.                         if ($id =~ /^COM[M ]?$/) { # space for iTunes brokenness
  560.                             $data =~ s/^(?:...)//;        # strip language
  561.                         }
  562.  
  563.                         if ($UNICODE) {
  564.                             if ($encoding eq "\001" || $encoding eq "\002") {  # UTF-16, UTF-16BE
  565.                                 # text fields can be null-separated lists;
  566.                                 # UTF-16 therefore needs special care
  567.                                 $data = join "\000", map { Encode::decode('utf16', $_) } split /\000\000/, $data;
  568.                             } elsif ($encoding eq "\003") { # UTF-8
  569.                                 # make sure string is UTF8, and set flag appropriately
  570.                                 $data = Encode::decode('utf8', $data);
  571.                             } elsif ($encoding eq "\000") {
  572.                                 # Try and guess the encoding, otherwise just use latin1
  573.                                 my $dec = Encode::Guess->guess($data);
  574.                                 if (ref $dec) {
  575.                                     $data = $dec->decode($data);
  576.                                 } else {
  577.                                     # Best try
  578.                                     $data = Encode::decode('iso-8859-1', $data);
  579.                                 }
  580.                             }
  581.  
  582.                             # do we care about trailing NULL?
  583.                             # $data =~ s/\000$//;
  584.  
  585.                         } else {
  586.                             # If the string starts with an
  587.                             # UTF-16 little endian BOM, use a hack to
  588.                             # convert to ASCII per best-effort
  589.                             my $pat;
  590.                             if ($data =~ s/^\xFF\xFE//) {
  591.                                 $pat = 'v';
  592.                             } elsif ($data =~ s/^\xFE\xFF//) {
  593.                                 $pat = 'n';
  594.                             }
  595.                             if ($pat) {
  596.                                 $data = pack 'C*', map {
  597.                                     (chr =~ /[[:ascii:]]/ && chr =~ /[[:print:]]/)
  598.                                         ? $_
  599.                                         : ord('?')
  600.                                 } unpack "$pat*", $data;
  601.                             }
  602.                         }
  603.  
  604.                         # We do this after decoding so we could be certain we're dealing
  605.                         # with 8-bit text.
  606.                         if ($id =~ /^COM[M ]?$/) { # space for iTunes brokenness
  607.                             $data =~ s/^(.*?)\000//;    # strip up to first NULL(s),
  608.                                             # for sub-comments (TODO:
  609.                                             # handle all comment data)
  610.                             $desc = $1;
  611.                         } elsif ($id =~ /^TCON?$/) {
  612.                             if ($data =~ /^ \(? (\d+) (?:\)|\000)? (.+)?/sx) {
  613.                                 my($index, $name) = ($1, $2);
  614.                                 if ($name && $name ne "\000") {
  615.                                     $data = $name;
  616.                                 } else {
  617.                                     $data = $mp3_genres[$index];
  618.                                 }
  619.                             }
  620.                         }
  621.  
  622.                         if ($raw_v2 == 2 && $desc) {
  623.                             $data = { $desc => $data };
  624.                         }
  625.  
  626.                         if ($raw_v2 == 2 && exists $info{$hash->{$id}}) {
  627.                             if (ref $info{$hash->{$id}} eq 'ARRAY') {
  628.                                 push @{$info{$hash->{$id}}}, $data;
  629.                             } else {
  630.                                 $info{$hash->{$id}} = [ $info{$hash->{$id}}, $data ];
  631.                             }
  632.                         } else {
  633.                             $info{$hash->{$id}} = $data;
  634.                         }
  635.                     }
  636.                 }
  637.             }
  638.             if ($ver == 0 && $info{TAGVERSION}) {
  639.                 $info{TAGVERSION} .= ' / ' . $v2h->{version};
  640.             } else {
  641.                 $info{TAGVERSION} = $v2h->{version};
  642.             }
  643.         }
  644.     }
  645.  
  646.     unless ($raw_v2 && $ver == 2) {
  647.         foreach my $key (keys %info) {
  648.             if (defined $info{$key}) {
  649.                 $info{$key} =~ s/\000+.*//g;
  650.                 $info{$key} =~ s/\s+$//;
  651.             }
  652.         }
  653.  
  654.         for (@v1_tag_names) {
  655.             $info{$_} = '' unless defined $info{$_};
  656.         }
  657.     }
  658.  
  659.     if (keys %info && exists $info{GENRE} && ! defined $info{GENRE}) {
  660.         $info{GENRE} = '';
  661.     }
  662.  
  663.     _close($file, $fh);
  664.  
  665.     return keys %info ? {%info} : undef;
  666. }
  667.  
  668. sub _get_v2tag {
  669.     my($fh) = @_;
  670.     my($off, $end, $myseek, $v2, $v2h, $hlen, $num, $wholetag);
  671.  
  672.     $v2 = {};
  673.     $v2h = _get_v2head($fh) or return;
  674.  
  675.     if ($v2h->{major_version} < 2) {
  676.         carp "This is $v2h->{version}; " .
  677.              "ID3v2 versions older than ID3v2.2.0 not supported\n"
  678.              if $^W;
  679.         return;
  680.     }
  681.  
  682.     # use syncsafe bytes if using version 2.4
  683.     my $bytesize = ($v2h->{major_version} > 3) ? 128 : 256;
  684.  
  685.     if ($v2h->{major_version} == 2) {
  686.         $hlen = 6;
  687.         $num = 3;
  688.     } else {
  689.         $hlen = 10;
  690.         $num = 4;
  691.     }
  692.  
  693.     $off = $v2h->{ext_header_size} + 10;
  694.     $end = $v2h->{tag_size} + 10; # should we read in the footer too?
  695.  
  696.     seek $fh, $v2h->{offset}, 0;
  697.     read $fh, $wholetag, $end;
  698.  
  699.     $wholetag =~ s/\xFF\x00/\xFF/gs if $v2h->{unsync};
  700.  
  701.     $myseek = sub {
  702.         my $bytes = substr($wholetag, $off, $hlen);
  703.         return unless $bytes =~ /^([A-Z0-9]{$num})/
  704.             || ($num == 4 && $bytes =~ /^(COM )/);  # stupid iTunes
  705.         my($id, $size) = ($1, $hlen);
  706.         my @bytes = reverse unpack "C$num", substr($bytes, $num, $num);
  707.  
  708.         for my $i (0 .. ($num - 1)) {
  709.             $size += $bytes[$i] * $bytesize ** $i;
  710.         }
  711.  
  712.         my $flags = {};
  713.         if ($v2h->{major_version} > 3) {
  714.             my @bits = split //, unpack 'B16', substr($bytes, 8, 2);
  715.             $flags->{frame_unsync}       = $bits[14];
  716.             $flags->{data_len_indicator} = $bits[15];
  717.         }
  718.  
  719.         return($id, $size, $flags);
  720.     };
  721.  
  722.     while ($off < $end) {
  723.         my($id, $size, $flags) = &$myseek or last;
  724.  
  725.         my $bytes = substr($wholetag, $off+$hlen, $size-$hlen);
  726.  
  727.         my $data_len;
  728.         if ($flags->{data_len_indicator}) {
  729.             $data_len = 0;
  730.             my @data_len_bytes = reverse unpack 'C4', substr($bytes, 0, 4);
  731.             $bytes = substr($bytes, 4);
  732.                 for my $i (0..3) {
  733.                 $data_len += $data_len_bytes[$i] * 128 ** $i;
  734.                 }
  735.         }
  736.  
  737.         # perform frame-level unsync if needed (skip if already done for whole tag)
  738.         $bytes =~ s/\xFF\x00/\xFF/gs if $flags->{frame_unsync} && !$v2h->{unsync};
  739.  
  740.         # if we know the data length, sanity check it now.
  741.         if ($flags->{data_len_indicator} && defined $data_len) {
  742.                 carp "Size mismatch on $id\n" unless $data_len == length($bytes);
  743.         }
  744.  
  745.         if (exists $v2->{$id}) {
  746.             if (ref $v2->{$id} eq 'ARRAY') {
  747.                 push @{$v2->{$id}}, $bytes;
  748.             } else {
  749.                 $v2->{$id} = [$v2->{$id}, $bytes];
  750.             }
  751.         } else {
  752.             $v2->{$id} = $bytes;
  753.         }
  754.         $off += $size;
  755.     }
  756.  
  757.     return($v2, $v2h);
  758. }
  759.  
  760.  
  761. =pod
  762.  
  763. =item get_mp3info (FILE)
  764.  
  765. Returns hash reference containing file information for MP3 file.
  766. This data cannot be changed.  Returned data:
  767.  
  768.     VERSION        MPEG audio version (1, 2, 2.5)
  769.     LAYER        MPEG layer description (1, 2, 3)
  770.     STEREO        boolean for audio is in stereo
  771.  
  772.     VBR        boolean for variable bitrate
  773.     BITRATE        bitrate in kbps (average for VBR files)
  774.     FREQUENCY    frequency in kHz
  775.     SIZE        bytes in audio stream
  776.  
  777.     SECS        total seconds
  778.     MM        minutes
  779.     SS        leftover seconds
  780.     MS        leftover milliseconds
  781.     TIME        time in MM:SS
  782.  
  783.     COPYRIGHT    boolean for audio is copyrighted
  784.     PADDING        boolean for MP3 frames are padded
  785.     MODE        channel mode (0 = stereo, 1 = joint stereo,
  786.             2 = dual channel, 3 = single channel)
  787.     FRAMES        approximate number of frames
  788.     FRAME_LENGTH    approximate length of a frame
  789.     VBR_SCALE    VBR scale from VBR header
  790.  
  791. On error, returns nothing and sets C<$@>.
  792.  
  793. =cut
  794.  
  795. sub get_mp3info {
  796.     my($file) = @_;
  797.     my($off, $byte, $eof, $h, $tot, $fh);
  798.  
  799.     if (not (defined $file && $file ne '')) {
  800.         $@ = "No file specified";
  801.         return undef;
  802.     }
  803.  
  804.     if (not -s $file) {
  805.         $@ = "File is empty";
  806.         return undef;
  807.     }
  808.  
  809.     if (ref $file) { # filehandle passed
  810.         $fh = $file;
  811.     } else {
  812.         if (not open $fh, '<', $file) {
  813.             $@ = "Can't open $file: $!";
  814.             return undef;
  815.         }
  816.     }
  817.  
  818.     $off = 0;
  819.     $tot = 8192;
  820.  
  821.     binmode $fh;
  822.     seek $fh, $off, 0;
  823.     read $fh, $byte, 4;
  824.  
  825.     if ($off == 0) {
  826.         if (my $v2h = _get_v2head($fh)) {
  827.             $tot += $off += $v2h->{tag_size};
  828.             seek $fh, $off, 0;
  829.             read $fh, $byte, 4;
  830.         }
  831.     }
  832.  
  833.     $h = _get_head($byte);
  834.     my $is_mp3 = _is_mp3($h); 
  835.     until ($is_mp3) {
  836.         $off++;
  837.         seek $fh, $off, 0;
  838.         read $fh, $byte, 4;
  839.         if ($off > $tot && !$try_harder) {
  840.             _close($file, $fh);
  841.             $@ = "Couldn't find MP3 header (perhaps set " .
  842.                  '$MP3::Info::try_harder and retry)';
  843.             return undef;
  844.         }
  845.         next if ord($byte) != 0xFF;
  846.         $h = _get_head($byte);
  847.         $is_mp3 = _is_mp3($h);
  848.     }
  849.  
  850.     my $vbr = _get_vbr($fh, $h, \$off);
  851.  
  852.     seek $fh, 0, 2;
  853.     $eof = tell $fh;
  854.     seek $fh, -128, 2;
  855.     $off += 128 if <$fh> =~ /^TAG/ ? 1 : 0;
  856.  
  857.     _close($file, $fh);
  858.  
  859.     $h->{size} = $eof - $off;
  860.  
  861.     return _get_info($h, $vbr);
  862. }
  863.  
  864. sub _get_info {
  865.     my($h, $vbr) = @_;
  866.     my $i;
  867.  
  868.     $i->{VERSION}    = $h->{IDR} == 2 ? 2 : $h->{IDR} == 3 ? 1 :
  869.                 $h->{IDR} == 0 ? 2.5 : 0;
  870.     $i->{LAYER}    = 4 - $h->{layer};
  871.     $i->{VBR}    = defined $vbr ? 1 : 0;
  872.  
  873.     $i->{COPYRIGHT}    = $h->{copyright} ? 1 : 0;
  874.     $i->{PADDING}    = $h->{padding_bit} ? 1 : 0;
  875.     $i->{STEREO}    = $h->{mode} == 3 ? 0 : 1;
  876.     $i->{MODE}    = $h->{mode};
  877.  
  878.     $i->{SIZE}    = $vbr && $vbr->{bytes} ? $vbr->{bytes} : $h->{size};
  879.  
  880.     my $mfs        = $h->{fs} / ($h->{ID} ? 144000 : 72000);
  881.     $i->{FRAMES}    = int($vbr && $vbr->{frames}
  882.                 ? $vbr->{frames}
  883.                 : $i->{SIZE} / ($h->{bitrate} / $mfs)
  884.               );
  885.  
  886.     if ($vbr) {
  887.         $i->{VBR_SCALE}    = $vbr->{scale} if $vbr->{scale};
  888.         $h->{bitrate}    = $i->{SIZE} / $i->{FRAMES} * $mfs;
  889.         if (not $h->{bitrate}) {
  890.             $@ = "Couldn't determine VBR bitrate";
  891.             return undef;
  892.         }
  893.     }
  894.  
  895.     $h->{'length'}    = ($i->{SIZE} * 8) / $h->{bitrate} / 10;
  896.     $i->{SECS}    = $h->{'length'} / 100;
  897.     $i->{MM}    = int $i->{SECS} / 60;
  898.     $i->{SS}    = int $i->{SECS} % 60;
  899.     $i->{MS}    = (($i->{SECS} - ($i->{MM} * 60) - $i->{SS}) * 1000);
  900. #    $i->{LF}    = ($i->{MS} / 1000) * ($i->{FRAMES} / $i->{SECS});
  901. #    int($i->{MS} / 100 * 75);  # is this right?
  902.     $i->{TIME}    = sprintf "%.2d:%.2d", @{$i}{'MM', 'SS'};
  903.  
  904.     $i->{BITRATE}        = int $h->{bitrate};
  905.     # should we just return if ! FRAMES?
  906.     $i->{FRAME_LENGTH}    = int($h->{size} / $i->{FRAMES}) if $i->{FRAMES};
  907.     $i->{FREQUENCY}        = $frequency_tbl[3 * $h->{IDR} + $h->{sampling_freq}];
  908.  
  909.     return $i;
  910. }
  911.  
  912. sub _get_head {
  913.     my($byte) = @_;
  914.     my($bytes, $h);
  915.  
  916.     $bytes = _unpack_head($byte);
  917.     @$h{qw(IDR ID layer protection_bit
  918.         bitrate_index sampling_freq padding_bit private_bit
  919.         mode mode_extension copyright original
  920.         emphasis version_index bytes)} = (
  921.         ($bytes>>19)&3, ($bytes>>19)&1, ($bytes>>17)&3, ($bytes>>16)&1,
  922.         ($bytes>>12)&15, ($bytes>>10)&3, ($bytes>>9)&1, ($bytes>>8)&1,
  923.         ($bytes>>6)&3, ($bytes>>4)&3, ($bytes>>3)&1, ($bytes>>2)&1,
  924.         $bytes&3, ($bytes>>19)&3, $bytes
  925.     );
  926.  
  927.     $h->{bitrate} = $t_bitrate[$h->{ID}][3 - $h->{layer}][$h->{bitrate_index}];
  928.     $h->{fs} = $t_sampling_freq[$h->{IDR}][$h->{sampling_freq}];
  929.  
  930.     return $h;
  931. }
  932.  
  933. sub _is_mp3 {
  934.     my $h = $_[0] or return undef;
  935.     return ! (    # all below must be false
  936.          $h->{bitrate_index} == 0
  937.             ||
  938.          $h->{version_index} == 1
  939.             ||
  940.         ($h->{bytes} & 0xFFE00000) != 0xFFE00000
  941.             ||
  942.         !$h->{fs}
  943.             ||
  944.         !$h->{bitrate}
  945.             ||
  946.          $h->{bitrate_index} == 15
  947.             ||
  948.         !$h->{layer}
  949.             ||
  950.          $h->{sampling_freq} == 3
  951.             ||
  952.          $h->{emphasis} == 2
  953.             ||
  954.         !$h->{bitrate_index}
  955.             ||
  956.         ($h->{bytes} & 0xFFFF0000) == 0xFFFE0000
  957.             ||
  958.         ($h->{ID} == 1 && $h->{layer} == 3 && $h->{protection_bit} == 1)
  959.             ||
  960.         ($h->{mode_extension} != 0 && $h->{mode} != 1)
  961.     );
  962. }
  963.  
  964. sub _get_vbr {
  965.     my($fh, $h, $roff) = @_;
  966.     my($off, $bytes, @bytes, $myseek, %vbr);
  967.  
  968.     $off = $$roff;
  969.     @_ = ();    # closure confused if we don't do this
  970.  
  971.     $myseek = sub {
  972.         my $n = $_[0] || 4;
  973.         seek $fh, $off, 0;
  974.         read $fh, $bytes, $n;
  975.         $off += $n;
  976.     };
  977.  
  978.     $off += 4;
  979.  
  980.     if ($h->{ID}) {    # MPEG1
  981.         $off += $h->{mode} == 3 ? 17 : 32;
  982.     } else {    # MPEG2
  983.         $off += $h->{mode} == 3 ? 9 : 17;
  984.     }
  985.  
  986.     &$myseek;
  987.     return unless $bytes eq 'Xing';
  988.  
  989.     &$myseek;
  990.     $vbr{flags} = _unpack_head($bytes);
  991.  
  992.     if ($vbr{flags} & 1) {
  993.         &$myseek;
  994.         $vbr{frames} = _unpack_head($bytes);
  995.     }
  996.  
  997.     if ($vbr{flags} & 2) {
  998.         &$myseek;
  999.         $vbr{bytes} = _unpack_head($bytes);
  1000.     }
  1001.  
  1002.     if ($vbr{flags} & 4) {
  1003.         $myseek->(100);
  1004. # Not used right now ...
  1005. #        $vbr{toc} = _unpack_head($bytes);
  1006.     }
  1007.  
  1008.     if ($vbr{flags} & 8) { # (quality ind., 0=best 100=worst)
  1009.         &$myseek;
  1010.         $vbr{scale} = _unpack_head($bytes);
  1011.     } else {
  1012.         $vbr{scale} = -1;
  1013.     }
  1014.  
  1015.     $$roff = $off;
  1016.     return \%vbr;
  1017. }
  1018.  
  1019. sub _get_v2head {
  1020.     my $fh = $_[0] or return;
  1021.     my($v2h, $bytes, @bytes);
  1022.     $v2h->{offset} = 0;
  1023.  
  1024.     # check first three bytes for 'ID3'
  1025.     seek $fh, 0, 0;
  1026.     read $fh, $bytes, 3;
  1027.  
  1028.     # TODO: add support for tags at the end of the file
  1029.     if ($bytes eq 'RIF' || $bytes eq 'FOR') {
  1030.         _find_id3_chunk($fh, $bytes) or return;
  1031.         $v2h->{offset} = tell $fh;
  1032.         read $fh, $bytes, 3;
  1033.     }
  1034.  
  1035.     return unless $bytes eq 'ID3';
  1036.  
  1037.     # get version
  1038.     read $fh, $bytes, 2;
  1039.     $v2h->{version} = sprintf "ID3v2.%d.%d",
  1040.         @$v2h{qw[major_version minor_version]} =
  1041.             unpack 'c2', $bytes;
  1042.  
  1043.     # get flags
  1044.     read $fh, $bytes, 1;
  1045.     my @bits = split //, unpack 'b8', $bytes;
  1046.     if ($v2h->{major_version} == 2) {
  1047.         $v2h->{unsync}       = $bits[7];
  1048.         $v2h->{compression}  = $bits[8];
  1049.         $v2h->{ext_header}   = 0;
  1050.         $v2h->{experimental} = 0;
  1051.     } else {
  1052.         $v2h->{unsync}       = $bits[7];
  1053.         $v2h->{ext_header}   = $bits[6];
  1054.         $v2h->{experimental} = $bits[5];
  1055.         $v2h->{footer}       = $bits[4] if $v2h->{major_version} == 4;
  1056.     }
  1057.  
  1058.     # get ID3v2 tag length from bytes 7-10
  1059.     $v2h->{tag_size} = 10;    # include ID3v2 header size
  1060.     $v2h->{tag_size} += 10 if $v2h->{footer};
  1061.     read $fh, $bytes, 4;
  1062.     @bytes = reverse unpack 'C4', $bytes;
  1063.     foreach my $i (0 .. 3) {
  1064.         # whoaaaaaa nellllllyyyyyy!
  1065.         $v2h->{tag_size} += $bytes[$i] * 128 ** $i;
  1066.     }
  1067.  
  1068.     # get extended header size
  1069.     $v2h->{ext_header_size} = 0;
  1070.     if ($v2h->{ext_header}) {
  1071.         read $fh, $bytes, 4;
  1072.         @bytes = reverse unpack 'C4', $bytes;
  1073.  
  1074.         # use syncsafe bytes if using version 2.4
  1075.         my $bytesize = ($v2h->{major_version} > 3) ? 128 : 256;
  1076.         for my $i (0..3) {
  1077.             $v2h->{ext_header_size} += $bytes[$i] * $bytesize ** $i;
  1078.         }
  1079.     }
  1080.  
  1081.     return $v2h;
  1082. }
  1083.  
  1084. sub _find_id3_chunk {
  1085.     my($fh, $filetype) = @_;
  1086.     my($bytes, $size, $tag, $pat, $mat);
  1087.  
  1088.     read $fh, $bytes, 1;
  1089.     if ($filetype eq 'RIF') {  # WAV
  1090.         return 0 if $bytes ne 'F';
  1091.         $pat = 'a4V';
  1092.         $mat = 'id3 ';
  1093.     } elsif ($filetype eq 'FOR') { # AIFF
  1094.         return 0 if $bytes ne 'M';
  1095.         $pat = 'a4N';
  1096.         $mat = 'ID3 ';
  1097.     }
  1098.     seek $fh, 12, 0;  # skip to the first chunk
  1099.  
  1100.     while ((read $fh, $bytes, 8) == 8) {
  1101.         ($tag, $size)  = unpack $pat, $bytes;
  1102.         return 1 if $tag eq $mat;
  1103.         seek $fh, $size, 1;
  1104.     }
  1105.  
  1106.     return 0;
  1107. }
  1108.  
  1109. sub _unpack_head {
  1110.     unpack('l', pack('L', unpack('N', $_[0])));
  1111. }
  1112.  
  1113. sub _close {
  1114.     my($file, $fh) = @_;
  1115.     unless (ref $file) { # filehandle not passed
  1116.         close $fh or carp "Problem closing '$file': $!";
  1117.     }
  1118. }
  1119.  
  1120. BEGIN {
  1121.     @mp3_genres = (
  1122.         'Blues',
  1123.         'Classic Rock',
  1124.         'Country',
  1125.         'Dance',
  1126.         'Disco',
  1127.         'Funk',
  1128.         'Grunge',
  1129.         'Hip-Hop',
  1130.         'Jazz',
  1131.         'Metal',
  1132.         'New Age',
  1133.         'Oldies',
  1134.         'Other',
  1135.         'Pop',
  1136.         'R&B',
  1137.         'Rap',
  1138.         'Reggae',
  1139.         'Rock',
  1140.         'Techno',
  1141.         'Industrial',
  1142.         'Alternative',
  1143.         'Ska',
  1144.         'Death Metal',
  1145.         'Pranks',
  1146.         'Soundtrack',
  1147.         'Euro-Techno',
  1148.         'Ambient',
  1149.         'Trip-Hop',
  1150.         'Vocal',
  1151.         'Jazz+Funk',
  1152.         'Fusion',
  1153.         'Trance',
  1154.         'Classical',
  1155.         'Instrumental',
  1156.         'Acid',
  1157.         'House',
  1158.         'Game',
  1159.         'Sound Clip',
  1160.         'Gospel',
  1161.         'Noise',
  1162.         'AlternRock',
  1163.         'Bass',
  1164.         'Soul',
  1165.         'Punk',
  1166.         'Space',
  1167.         'Meditative',
  1168.         'Instrumental Pop',
  1169.         'Instrumental Rock',
  1170.         'Ethnic',
  1171.         'Gothic',
  1172.         'Darkwave',
  1173.         'Techno-Industrial',
  1174.         'Electronic',
  1175.         'Pop-Folk',
  1176.         'Eurodance',
  1177.         'Dream',
  1178.         'Southern Rock',
  1179.         'Comedy',
  1180.         'Cult',
  1181.         'Gangsta',
  1182.         'Top 40',
  1183.         'Christian Rap',
  1184.         'Pop/Funk',
  1185.         'Jungle',
  1186.         'Native American',
  1187.         'Cabaret',
  1188.         'New Wave',
  1189.         'Psychadelic',
  1190.         'Rave',
  1191.         'Showtunes',
  1192.         'Trailer',
  1193.         'Lo-Fi',
  1194.         'Tribal',
  1195.         'Acid Punk',
  1196.         'Acid Jazz',
  1197.         'Polka',
  1198.         'Retro',
  1199.         'Musical',
  1200.         'Rock & Roll',
  1201.         'Hard Rock',
  1202.     );
  1203.  
  1204.     @winamp_genres = (
  1205.         @mp3_genres,
  1206.         'Folk',
  1207.         'Folk-Rock',
  1208.         'National Folk',
  1209.         'Swing',
  1210.         'Fast Fusion',
  1211.         'Bebop',
  1212.         'Latin',
  1213.         'Revival',
  1214.         'Celtic',
  1215.         'Bluegrass',
  1216.         'Avantgarde',
  1217.         'Gothic Rock',
  1218.         'Progressive Rock',
  1219.         'Psychedelic Rock',
  1220.         'Symphonic Rock',
  1221.         'Slow Rock',
  1222.         'Big Band',
  1223.         'Chorus',
  1224.         'Easy Listening',
  1225.         'Acoustic',
  1226.         'Humour',
  1227.         'Speech',
  1228.         'Chanson',
  1229.         'Opera',
  1230.         'Chamber Music',
  1231.         'Sonata',
  1232.         'Symphony',
  1233.         'Booty Bass',
  1234.         'Primus',
  1235.         'Porn Groove',
  1236.         'Satire',
  1237.         'Slow Jam',
  1238.         'Club',
  1239.         'Tango',
  1240.         'Samba',
  1241.         'Folklore',
  1242.         'Ballad',
  1243.         'Power Ballad',
  1244.         'Rhythmic Soul',
  1245.         'Freestyle',
  1246.         'Duet',
  1247.         'Punk Rock',
  1248.         'Drum Solo',
  1249.         'Acapella',
  1250.         'Euro-House',
  1251.         'Dance Hall',
  1252.         'Goa',
  1253.         'Drum & Bass',
  1254.         'Club-House',
  1255.         'Hardcore',
  1256.         'Terror',
  1257.         'Indie',
  1258.         'BritPop',
  1259.         'Negerpunk',
  1260.         'Polsk Punk',
  1261.         'Beat',
  1262.         'Christian Gangsta Rap',
  1263.         'Heavy Metal',
  1264.         'Black Metal',
  1265.         'Crossover',
  1266.         'Contemporary Christian',
  1267.         'Christian Rock',
  1268.         'Merengue',
  1269.         'Salsa',
  1270.         'Thrash Metal',
  1271.         'Anime',
  1272.         'JPop',
  1273.         'Synthpop',
  1274.     );
  1275.  
  1276.     @t_bitrate = ([
  1277.         [0, 32, 48, 56,  64,  80,  96, 112, 128, 144, 160, 176, 192, 224, 256],
  1278.         [0,  8, 16, 24,  32,  40,  48,  56,  64,  80,  96, 112, 128, 144, 160],
  1279.         [0,  8, 16, 24,  32,  40,  48,  56,  64,  80,  96, 112, 128, 144, 160]
  1280.     ],[
  1281.         [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448],
  1282.         [0, 32, 48, 56,  64,  80,  96, 112, 128, 160, 192, 224, 256, 320, 384],
  1283.         [0, 32, 40, 48,  56,  64,  80,  96, 112, 128, 160, 192, 224, 256, 320]
  1284.     ]);
  1285.  
  1286.     @t_sampling_freq = (
  1287.         [11025, 12000,  8000],
  1288.         [undef, undef, undef],    # reserved
  1289.         [22050, 24000, 16000],
  1290.         [44100, 48000, 32000]
  1291.     );
  1292.  
  1293.     @frequency_tbl = map { $_ ? eval "${_}e-3" : 0 }
  1294.         map { @$_ } @t_sampling_freq;
  1295.  
  1296.     @mp3_info_fields = qw(
  1297.         VERSION
  1298.         LAYER
  1299.         STEREO
  1300.         VBR
  1301.         BITRATE
  1302.         FREQUENCY
  1303.         SIZE
  1304.         SECS
  1305.         MM
  1306.         SS
  1307.         MS
  1308.         TIME
  1309.         COPYRIGHT
  1310.         PADDING
  1311.         MODE
  1312.         FRAMES
  1313.         FRAME_LENGTH
  1314.         VBR_SCALE
  1315.     );
  1316.  
  1317.     %v1_tag_fields =
  1318.         (TITLE => 30, ARTIST => 30, ALBUM => 30, COMMENT => 30, YEAR => 4);
  1319.  
  1320.     @v1_tag_names = qw(TITLE ARTIST ALBUM YEAR COMMENT TRACKNUM GENRE);
  1321.  
  1322.     %v2_to_v1_names = (
  1323.         # v2.2 tags
  1324.         'TT2' => 'TITLE',
  1325.         'TP1' => 'ARTIST',
  1326.         'TAL' => 'ALBUM',
  1327.         'TYE' => 'YEAR',
  1328.         'COM' => 'COMMENT',
  1329.         'TRK' => 'TRACKNUM',
  1330.         'TCO' => 'GENRE', # not clean mapping, but ...
  1331.         # v2.3 tags
  1332.         'TIT2' => 'TITLE',
  1333.         'TPE1' => 'ARTIST',
  1334.         'TALB' => 'ALBUM',
  1335.         'TYER' => 'YEAR',
  1336.         'COMM' => 'COMMENT',
  1337.         'TRCK' => 'TRACKNUM',
  1338.         'TCON' => 'GENRE',
  1339.     );
  1340.  
  1341.     %v2_tag_names = (
  1342.         # v2.2 tags
  1343.         'BUF' => 'Recommended buffer size',
  1344.         'CNT' => 'Play counter',
  1345.         'COM' => 'Comments',
  1346.         'CRA' => 'Audio encryption',
  1347.         'CRM' => 'Encrypted meta frame',
  1348.         'ETC' => 'Event timing codes',
  1349.         'EQU' => 'Equalization',
  1350.         'GEO' => 'General encapsulated object',
  1351.         'IPL' => 'Involved people list',
  1352.         'LNK' => 'Linked information',
  1353.         'MCI' => 'Music CD Identifier',
  1354.         'MLL' => 'MPEG location lookup table',
  1355.         'PIC' => 'Attached picture',
  1356.         'POP' => 'Popularimeter',
  1357.         'REV' => 'Reverb',
  1358.         'RVA' => 'Relative volume adjustment',
  1359.         'SLT' => 'Synchronized lyric/text',
  1360.         'STC' => 'Synced tempo codes',
  1361.         'TAL' => 'Album/Movie/Show title',
  1362.         'TBP' => 'BPM (Beats Per Minute)',
  1363.         'TCM' => 'Composer',
  1364.         'TCO' => 'Content type',
  1365.         'TCR' => 'Copyright message',
  1366.         'TDA' => 'Date',
  1367.         'TDY' => 'Playlist delay',
  1368.         'TEN' => 'Encoded by',
  1369.         'TFT' => 'File type',
  1370.         'TIM' => 'Time',
  1371.         'TKE' => 'Initial key',
  1372.         'TLA' => 'Language(s)',
  1373.         'TLE' => 'Length',
  1374.         'TMT' => 'Media type',
  1375.         'TOA' => 'Original artist(s)/performer(s)',
  1376.         'TOF' => 'Original filename',
  1377.         'TOL' => 'Original Lyricist(s)/text writer(s)',
  1378.         'TOR' => 'Original release year',
  1379.         'TOT' => 'Original album/Movie/Show title',
  1380.         'TP1' => 'Lead artist(s)/Lead performer(s)/Soloist(s)/Performing group',
  1381.         'TP2' => 'Band/Orchestra/Accompaniment',
  1382.         'TP3' => 'Conductor/Performer refinement',
  1383.         'TP4' => 'Interpreted, remixed, or otherwise modified by',
  1384.         'TPA' => 'Part of a set',
  1385.         'TPB' => 'Publisher',
  1386.         'TRC' => 'ISRC (International Standard Recording Code)',
  1387.         'TRD' => 'Recording dates',
  1388.         'TRK' => 'Track number/Position in set',
  1389.         'TSI' => 'Size',
  1390.         'TSS' => 'Software/hardware and settings used for encoding',
  1391.         'TT1' => 'Content group description',
  1392.         'TT2' => 'Title/Songname/Content description',
  1393.         'TT3' => 'Subtitle/Description refinement',
  1394.         'TXT' => 'Lyricist/text writer',
  1395.         'TXX' => 'User defined text information frame',
  1396.         'TYE' => 'Year',
  1397.         'UFI' => 'Unique file identifier',
  1398.         'ULT' => 'Unsychronized lyric/text transcription',
  1399.         'WAF' => 'Official audio file webpage',
  1400.         'WAR' => 'Official artist/performer webpage',
  1401.         'WAS' => 'Official audio source webpage',
  1402.         'WCM' => 'Commercial information',
  1403.         'WCP' => 'Copyright/Legal information',
  1404.         'WPB' => 'Publishers official webpage',
  1405.         'WXX' => 'User defined URL link frame',
  1406.  
  1407.         # v2.3 tags
  1408.         'AENC' => 'Audio encryption',
  1409.         'APIC' => 'Attached picture',
  1410.         'COMM' => 'Comments',
  1411.         'COMR' => 'Commercial frame',
  1412.         'ENCR' => 'Encryption method registration',
  1413.         'EQUA' => 'Equalization',
  1414.         'ETCO' => 'Event timing codes',
  1415.         'GEOB' => 'General encapsulated object',
  1416.         'GRID' => 'Group identification registration',
  1417.         'IPLS' => 'Involved people list',
  1418.         'LINK' => 'Linked information',
  1419.         'MCDI' => 'Music CD identifier',
  1420.         'MLLT' => 'MPEG location lookup table',
  1421.         'OWNE' => 'Ownership frame',
  1422.         'PCNT' => 'Play counter',
  1423.         'POPM' => 'Popularimeter',
  1424.         'POSS' => 'Position synchronisation frame',
  1425.         'PRIV' => 'Private frame',
  1426.         'RBUF' => 'Recommended buffer size',
  1427.         'RVAD' => 'Relative volume adjustment',
  1428.         'RVRB' => 'Reverb',
  1429.         'SYLT' => 'Synchronized lyric/text',
  1430.         'SYTC' => 'Synchronized tempo codes',
  1431.         'TALB' => 'Album/Movie/Show title',
  1432.         'TBPM' => 'BPM (beats per minute)',
  1433.         'TCOM' => 'Composer',
  1434.         'TCON' => 'Content type',
  1435.         'TCOP' => 'Copyright message',
  1436.         'TDAT' => 'Date',
  1437.         'TDLY' => 'Playlist delay',
  1438.         'TENC' => 'Encoded by',
  1439.         'TEXT' => 'Lyricist/Text writer',
  1440.         'TFLT' => 'File type',
  1441.         'TIME' => 'Time',
  1442.         'TIT1' => 'Content group description',
  1443.         'TIT2' => 'Title/songname/content description',
  1444.         'TIT3' => 'Subtitle/Description refinement',
  1445.         'TKEY' => 'Initial key',
  1446.         'TLAN' => 'Language(s)',
  1447.         'TLEN' => 'Length',
  1448.         'TMED' => 'Media type',
  1449.         'TOAL' => 'Original album/movie/show title',
  1450.         'TOFN' => 'Original filename',
  1451.         'TOLY' => 'Original lyricist(s)/text writer(s)',
  1452.         'TOPE' => 'Original artist(s)/performer(s)',
  1453.         'TORY' => 'Original release year',
  1454.         'TOWN' => 'File owner/licensee',
  1455.         'TPE1' => 'Lead performer(s)/Soloist(s)',
  1456.         'TPE2' => 'Band/orchestra/accompaniment',
  1457.         'TPE3' => 'Conductor/performer refinement',
  1458.         'TPE4' => 'Interpreted, remixed, or otherwise modified by',
  1459.         'TPOS' => 'Part of a set',
  1460.         'TPUB' => 'Publisher',
  1461.         'TRCK' => 'Track number/Position in set',
  1462.         'TRDA' => 'Recording dates',
  1463.         'TRSN' => 'Internet radio station name',
  1464.         'TRSO' => 'Internet radio station owner',
  1465.         'TSIZ' => 'Size',
  1466.         'TSRC' => 'ISRC (international standard recording code)',
  1467.         'TSSE' => 'Software/Hardware and settings used for encoding',
  1468.         'TXXX' => 'User defined text information frame',
  1469.         'TYER' => 'Year',
  1470.         'UFID' => 'Unique file identifier',
  1471.         'USER' => 'Terms of use',
  1472.         'USLT' => 'Unsychronized lyric/text transcription',
  1473.         'WCOM' => 'Commercial information',
  1474.         'WCOP' => 'Copyright/Legal information',
  1475.         'WOAF' => 'Official audio file webpage',
  1476.         'WOAR' => 'Official artist/performer webpage',
  1477.         'WOAS' => 'Official audio source webpage',
  1478.         'WORS' => 'Official internet radio station homepage',
  1479.         'WPAY' => 'Payment',
  1480.         'WPUB' => 'Publishers official webpage',
  1481.         'WXXX' => 'User defined URL link frame',
  1482.  
  1483.         # v2.4 additional tags
  1484.         # note that we don't restrict tags from 2.3 or 2.4,
  1485.         'ASPI' => 'Audio seek point index',
  1486.         'EQU2' => 'Equalisation (2)',
  1487.         'RVA2' => 'Relative volume adjustment (2)',
  1488.         'SEEK' => 'Seek frame',
  1489.         'SIGN' => 'Signature frame',
  1490.         'TDEN' => 'Encoding time',
  1491.         'TDOR' => 'Original release time',
  1492.         'TDRC' => 'Recording time',
  1493.         'TDRL' => 'Release time',
  1494.         'TDTG' => 'Tagging time',
  1495.         'TIPL' => 'Involved people list',
  1496.         'TMCL' => 'Musician credits list',
  1497.         'TMOO' => 'Mood',
  1498.         'TPRO' => 'Produced notice',
  1499.         'TSOA' => 'Album sort order',
  1500.         'TSOP' => 'Performer sort order',
  1501.         'TSOT' => 'Title sort order',
  1502.         'TSST' => 'Set subtitle',
  1503.  
  1504.         # grrrrrrr
  1505.         'COM ' => 'Broken iTunes comments',
  1506.     );
  1507. }
  1508.  
  1509. 1;
  1510.  
  1511. __END__
  1512.  
  1513. =pod
  1514.  
  1515. =back
  1516.  
  1517. =head1 TROUBLESHOOTING
  1518.  
  1519. If you find a bug, please send me a patch (see the project page in L<"SEE ALSO">).
  1520. If you cannot figure out why it does not work for you, please put the MP3 file in
  1521. a place where I can get it (preferably via FTP, or HTTP, or .Mac iDisk) and send me
  1522. mail regarding where I can get the file, with a detailed description of the problem.
  1523.  
  1524. If I download the file, after debugging the problem I will not keep the MP3 file
  1525. if it is not legal for me to have it.  Just let me know if it is legal for me to
  1526. keep it or not.
  1527.  
  1528.  
  1529. =head1 TODO
  1530.  
  1531. =over 4
  1532.  
  1533. =item ID3v2 Support
  1534.  
  1535. Still need to do more for reading tags, such as using Compress::Zlib to decompress
  1536. compressed tags.  But until I see this in use more, I won't bother.  If something
  1537. does not work properly with reading, follow the instructions above for
  1538. troubleshooting.
  1539.  
  1540. ID3v2 I<writing> is coming soon.
  1541.  
  1542. =item Get data from scalar
  1543.  
  1544. Instead of passing a file spec or filehandle, pass the
  1545. data itself.  Would take some work, converting the seeks, etc.
  1546.  
  1547. =item Padding bit ?
  1548.  
  1549. Do something with padding bit.
  1550.  
  1551. =item Test suite
  1552.  
  1553. Test suite could use a bit of an overhaul and update.  Patches very welcome.
  1554.  
  1555. =over 4
  1556.  
  1557. =item *
  1558.  
  1559. Revamp getset.t.  Test all the various get_mp3tag args.
  1560.  
  1561. =item *
  1562.  
  1563. Test Unicode.
  1564.  
  1565. =item *
  1566.  
  1567. Test OOP API.
  1568.  
  1569. =item *
  1570.  
  1571. Test error handling, check more for missing files, bad MP3s, etc.
  1572.  
  1573. =back
  1574.  
  1575. =item Other VBR
  1576.  
  1577. Right now, only Xing VBR is supported.
  1578.  
  1579. =back
  1580.  
  1581.  
  1582. =head1 THANKS
  1583.  
  1584. Edward Allen,
  1585. Vittorio Bertola,
  1586. Michael Blakeley,
  1587. Per Bolmstedt,
  1588. Tony Bowden,
  1589. Tom Brown,
  1590. Sergio Camarena,
  1591. Chris Dawson,
  1592. Anthony DiSante,
  1593. Luke Drumm,
  1594. Kyle Farrell,
  1595. Jeffrey Friedl,
  1596. brian d foy,
  1597. Ben Gertzfield,
  1598. Brian Goodwin,
  1599. Todd Hanneken,
  1600. Todd Harris,
  1601. Woodrow Hill,
  1602. Kee Hinckley,
  1603. Roman Hodek,
  1604. Ilya Konstantinov,
  1605. Peter Kovacs,
  1606. Johann Lindvall,
  1607. Alex Marandon,
  1608. Peter Marschall,
  1609. michael,
  1610. Trond Michelsen,
  1611. Dave O'Neill,
  1612. Christoph Oberauer,
  1613. Jake Palmer,
  1614. Andrew Phillips,
  1615. David Reuteler,
  1616. John Ruttenberg,
  1617. Matthew Sachs,
  1618. scfc_de,
  1619. Hermann Schwaerzler,
  1620. Chris Sidi,
  1621. Roland Steinbach,
  1622. Brian S. Stephan,
  1623. Stuart,
  1624. Dan Sully,
  1625. Jeffery Sumler,
  1626. Predrag Supurovic,
  1627. Bogdan Surdu,
  1628. Pierre-Yves Thoulon,
  1629. tim,
  1630. Pass F. B. Travis,
  1631. Tobias Wagener,
  1632. Ronan Waide,
  1633. Andy Waite,
  1634. Ken Williams,
  1635. Ben Winslow,
  1636. Meng Weng Wong.
  1637.  
  1638.  
  1639. =head1 AUTHOR AND COPYRIGHT
  1640.  
  1641. Chris Nandor E<lt>pudge@pobox.comE<gt>, http://pudge.net/
  1642.  
  1643. Copyright (c) 1998-2004 Chris Nandor.  All rights reserved.  This program
  1644. is free software; you can redistribute it and/or modify it under the same
  1645. terms as Perl itself.
  1646.  
  1647.  
  1648. =head1 SEE ALSO
  1649.  
  1650. =over 4
  1651.  
  1652. =item MP3::Info Project Page
  1653.  
  1654.     http://projects.pudge.net/
  1655.  
  1656. =item mp3tools
  1657.  
  1658.     http://www.zevils.com/linux/mp3tools/
  1659.  
  1660. =item mpgtools
  1661.  
  1662.     http://www.dv.co.yu/mpgscript/mpgtools.htm
  1663.     http://www.dv.co.yu/mpgscript/mpeghdr.htm
  1664.  
  1665. =item mp3tool
  1666.  
  1667.     http://www.dtek.chalmers.se/~d2linjo/mp3/mp3tool.html
  1668.  
  1669. =item ID3v2
  1670.  
  1671.     http://www.id3.org/
  1672.  
  1673. =item Xing Variable Bitrate
  1674.  
  1675.     http://www.xingtech.com/support/partner_developer/mp3/vbr_sdk/
  1676.  
  1677. =item MP3Ext
  1678.  
  1679.     http://rupert.informatik.uni-stuttgart.de/~mutschml/MP3ext/
  1680.  
  1681. =item Xmms
  1682.  
  1683.     http://www.xmms.org/
  1684.  
  1685.  
  1686. =back
  1687.  
  1688. =cut
  1689.